package com.travel.server.manager.impl.command.customer;

import com.alibaba.fastjson.JSON;
import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.CommonUtil;
import com.travel.server.manager.dto.request.customer.UpdateCustomerOtherInfoRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.CustomerDal;
import com.travel.server.manager.impl.dal.CustomerDal.CustomerParam;
import com.travel.server.manager.impl.dal.CustomerTagDal;
import com.travel.server.manager.impl.dal.CustomerTagDal.CustomerTagParam;
import com.travel.server.manager.impl.dal.MemberGradeDal;
import com.travel.server.manager.impl.dal.TagDal;
import com.travel.server.manager.impl.sal.CustomerSal;
import com.travel.server.manager.model.CustomerInfo;
import com.travel.server.manager.model.CustomerTagInfo;
import com.travel.server.manager.model.MemberGradeInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/9 18:05
 * @Desc:
 */
@Component
@Slf4j
public class UpdateCustomerOtherInfoCommand extends AbstractCommand<UpdateCustomerOtherInfoRequest, EmptyResponse> {

    @Autowired
    private CustomerDal customerDal;

    @Autowired
    private TagDal tagDal;

    @Autowired
    private MemberGradeDal memberGradeDal;

    @Autowired
    private CustomerTagDal customerTagDal;

    @Override
    protected void checkInput(UpdateCustomerOtherInfoRequest request) {
        if(StringUtils.isBlank(request.getIdList())){
            throwInvalidParam();
        }
        if(request.getMemberGradeId() == null && request.getTagId() == null && StringUtils.isBlank(request.getScore())){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(UpdateCustomerOtherInfoRequest request) {
        checkInput(request);

        List<Integer> idList = CommonUtil.idsToList(request.getIdList());
        //查出客户信息
        CustomerParam customerParam = new CustomerParam();
        customerParam.setIdList(idList);
        List<CustomerInfo> customerList = customerDal.selectByExample(customerParam);
        if(CollectionUtil.isEmpty(customerList)){
            log.error("id列表未查询到客户信息, idList {}", JSON.toJSONString(idList));
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        if(request.getMemberGradeId() != null){
            updateMemberGrade(customerList, request.getMemberGradeId());
        }
        if(request.getTagId() != null){
            updateTag(customerList, request.getTagId());
        }
        if(StringUtils.isNotBlank(request.getScore())){
            updateScore(customerList, request.getScore());
        }

        return new EmptyResponse();
    }

    private void updateScore(List<CustomerInfo> list, String score){
        Integer scoreInt = Integer.parseInt(score);
        for(CustomerInfo customerInfo : list){
            String customerScore = customerInfo.getAvailableScores();
            if(StringUtils.isBlank(customerScore)){
                customerInfo.setAvailableScores(score);
            }else{
                Integer nowScore = scoreInt + Integer.parseInt(customerInfo.getAvailableScores());
                customerInfo.setAvailableScores(nowScore + CommonConstant.EMPTY_STR);
            }
            updateCustomer(customerInfo);
        }
    }

    private void updateTag(List<CustomerInfo> list, Integer tagId){
        tagDal.selectById(tagId);
        Date now = new Date();
        UserInfo userInfo = getUserInfo();
        for(CustomerInfo customerInfo : list){
            //查询用户是否存在对应标签
            CustomerTagParam param = new CustomerTagParam();
            param.setCustomerId(customerInfo.getId());
            param.setTagIdList(Arrays.asList(tagId));
            param.setState(null);
            CustomerTagInfo customerTagInfo = CollectionUtil.getFirst(customerTagDal.selectByExample(param));
            if(customerTagInfo == null){
                customerTagInfo = new CustomerTagInfo();
                customerTagInfo.setUpdateTime(now);
                customerTagInfo.setCreateTime(now);
                customerTagInfo.setUpdateBy(userInfo.getName());
                customerTagInfo.setCreateBy(userInfo.getName());
                customerTagInfo.setState(CommonConstant.YES);
                customerTagInfo.setTagId(tagId);
                customerTagInfo.setCustomerId(customerInfo.getId());
                customerTagDal.insertOrUpdate(customerTagInfo);
            }else{
                if(customerTagInfo.getState().equals(CommonConstant.NO)){
                    customerTagInfo.setState(CommonConstant.YES);
                    customerTagInfo.setUpdateBy(userInfo.getName());
                    customerTagInfo.setUpdateTime(now);
                    customerTagDal.insertOrUpdate(customerTagInfo);
                }
            }
        }
    }

    private void updateMemberGrade(List<CustomerInfo> list, Integer memberGradeId){
        MemberGradeInfo memberGradeInfo = memberGradeDal.selectById(memberGradeId);
        Integer isMember = CustomerSal.isMember(memberGradeInfo);
        for(CustomerInfo customerInfo : list){
            customerInfo.setMemberGradeId(memberGradeId);
            customerInfo.setIsMember(isMember);
            updateCustomer(customerInfo);
        }
    }

    private void updateCustomer(CustomerInfo customerInfo){
        UserInfo userInfo = getUserInfo();
        customerInfo.setUpdateBy(userInfo.getName());
        customerInfo.setUpdateTime(new Date());
        customerDal.insertOrUpdate(customerInfo);
    }
}
